var app = angular.module('compta', ['i18n','statements']).
    config(['$routeProvider', function($routeProvider) {
        $routeProvider.
            when('/', {templateUrl: 'app/partials/home.html',   controller: HomeCtrl}).
            when('/404', {templateUrl: 'app/partials/404.html'}).
            when('/accounting/:year/:month', {templateUrl: 'app/partials/accounting.html',   controller: AccountingCtrl}).
            when('/accounting/:year', {templateUrl: 'app/partials/accounting.html',   controller: AccountingCtrl}).
            otherwise({redirectTo: '/404'});
    }]);

app.run(function($http,$rootScope,taffy) {
    $rootScope.store = {};
    $http.get('initial-data/store.json')
        .then(function(response){
            $rootScope.store = response.data;
        });

    $http.get('initial-data/database.json')
        .then(function(response){
                for(var dbname in response.data){
                    if(!localStorage["taffy_" + dbname]){
                        var db = taffy.open(dbname);
                        for(var rowIdx in response.data[dbname]){
                            var row = response.data[dbname][rowIdx];
                            row.id = db.nextId();
                            db.insert(row);
                        }
                    }
                }
            });
});

app.factory('utils', function($location) {
    var utils = {};
    utils.notFound = function() {
        $location.path( "/404" );
    };
    utils.notFoundIfNull = function(object) {
        if(object == null){
            utils.notFound();
        }
    };
    return utils;
});

app.factory('dateUtils', function($rootScope) {
    var dateUtils = {};
    dateUtils.isValidMonth = function(month) {
        return $.inArray(month,$rootScope.store.months) > -1;
    };
    dateUtils.isValidYear = function(year) {
        return !isNaN(year) && year.length == 4;
    };
    dateUtils.getMonthNumber = function(month){
        return dateUtils.pad($rootScope.store.months.indexOf(month) + 1);
    };
    dateUtils.getMonthName = function(number){
        return $rootScope.store.months[number - 1];
    };
    dateUtils.pad = function(number){
        return (number < 10 ? '0' : '') + number;
    };
    dateUtils.toSQLFormat = function(year,month,day){
        return year + "-" + month + "-" + dateUtils.pad(day);
    };
    return dateUtils;
});

app.factory('taffy', function() {
    var taffy = {};
    taffy.open = function (name){
        var db = TAFFY();
        db.store(name);
        db.nextId = function(){
            var maxId = db().max("id");
            return (maxId != null ? maxId : 0) + 1;
        };
        return db;
    };
    return taffy;
});